<template>
  <div>
    <a-layout id="components-layout-demo-fixed-sider" style="margin-top: 24px;">
      <a-layout>
        <a-card :bordered="false" title="基本信息">
          <bis-house-content-base
            ref="baseForm"
            @change="handleFormChange"
            :title="getTitle"
            :region="getRegion"
            :structure="getStructure"
            :sellType="getSellType"
            :address="getAddress"
            :money="getMoney"
            :unit="getUnit"></bis-house-content-base>
        </a-card>
        <a-card :bordered="false" title="详情描述" style="margin-top:24px;">
          <vue-ueditor-wrap v-model="bisHouse.content" :config="myConfig" :destroy="true"></vue-ueditor-wrap>
        </a-card>
        <a-card :bordered="false" title="简述摘要" style="margin-top:24px;">
          <a-button @click="extractor" slot="extra" type="primary">生成摘要</a-button>
          <a-textarea placeholder="手工简述，或点击生成摘要按钮(将从详情描述中抽取摘要)" autosize v-model="bisHouse.summary"/>
        </a-card>
      </a-layout>
      <a-layout-sider class="r-layout-slide" style="margin-left: 24px; min-width: 300px;">
        <a-card :bordered="false" title="封面图片">
          <bis-house-upload-cover @watchCoverId="watchCoverId" :coverFiles="coverFiles"></bis-house-upload-cover>
        </a-card>
        <a-card :bordered="false" title="轮播图片" style="margin-top:24px;">
          <a-upload
            :action="uploadAction"
            listType="picture"
            :headers="headers"
            :defaultFileList="slideList"
            :remove="removeSlide"
            @change="afterSlideUpload">
            <a-button v-if="this.slideList.length < 3">
              <a-icon type="upload" /> 点击上传
            </a-button>
          </a-upload>
        </a-card>
      </a-layout-sider>
    </a-layout>
    <footer-tool-bar>
      <a-button @click="handleSubmit" type="primary">提交</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
  import BisHouseContentBase from './house/BisHouseContentBase'
  import BisHouseContentFile from './house/BisHouseContentFile'
  import BisHouseUploadCover from './house/BisHouseUploadCover'
  import FooterToolBar from '@/components/tools/FooterToolBar'
  import {extractorSummary, addHouse,editHouse, queryHouse} from '@/api/api'
  import VueUeditorWrap from 'vue-ueditor-wrap'
  import { ACCESS_TOKEN } from "@/store/mutation-types"

  export default {
    name: "BisHouseContent",
    components: {
      BisHouseContentBase,
      BisHouseContentFile,
      BisHouseUploadCover,
      FooterToolBar,
      VueUeditorWrap
    },
    data() {
      return {
        myConfig: {
          // 如果需要上传功能,找后端小伙伴要服务器接口地址
          // serverUrl: this.$config.baseUrl + 'ueditor/ueditorConfig',
          serverUrl: window._CONFIG['domianURL'] + '/sys/ueditor/config',
          //<img src="http://35.201.165.105:8000/storage/image/20190421/1555835121507355.jpg" title="1555835121507355.jpg" alt="timg.jpg"/>
          // serverUrl: 'http://35.201.165.105:8000/controller.php',
          // 你的UEditor资源存放的路径,相对于打包后的index.html
          UEDITOR_HOME_URL: '/ueditor/',
          // 编辑器不自动被内容撑高
          autoHeightEnabled: true,
          // 工具栏是否可以浮动
          autoFloatEnabled: true,
          // 初始容器高度
          initialFrameHeight: 340,
          // 初始容器宽度
          initialFrameWidth: '100%',
          // 关闭自动保存
          enableAutoSave: true,
          // 编辑器在页面上的z-index层级的基数，默认是900
          zIndex: 0,
          iframeCssUrl: '/ueditor/themes/iframe.css'
        },
        bisHouse: {
          id: null,
          title: null,
          region: null,
          address: null,
          structure: null,
          money: null,
          unit: null,
          sellType: null,
          summary: '',
          content: '',
          createTime: null
        },
        coverFiles: [],
        coverId: null,
        slideList: [],
        uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
        headers: {'X-Access-Token': this.$ls.get(ACCESS_TOKEN)},
      }
    },
    created() {
      const houseId = this.$route.params.houseId
      if(houseId) {
        queryHouse({id: houseId}).then(res => {
          if(res.result.bisHouse) {
            this.bisHouse = res.result.bisHouse
          }
          if(res.result.cover) {
            const obj = {uid:res.result.cover.id, name:res.result.cover.originalFileName,url:window._CONFIG['domianURL']+'/'+res.result.cover.relativePath}
            this.coverFiles.push(obj)
            this.coverId = res.result.cover.id
          }
          if(res.result.slides && res.result.slides.length > 0) {
            res.result.slides.forEach((item) => {
              const slide = {uid:item.id, name:item.originalFileName, status:'done', url:window._CONFIG['domianURL']+'/'+item.relativePath, thumbUrl: window._CONFIG['domianURL']+'/'+item.relativePath}
              this.slideList.push(slide)
            })
          }
        })
      }
    },
    methods: {
      extractor() {
        if(this.bisHouse.content == null || this.bisHouse.content == undefined || this.bisHouse.content === '') {
          this.$notification['error']({
            message: '错误',
            description: '详情描述中没有任何内容',
          })
        }else {
          const param = {
            html: this.bisHouse.content,
            length: 60
          }
          extractorSummary(param).then(res => {
            this.bisHouse.summary = res.result
          })
        }
      },
      handleFormChange (changedFields) {
        Object.keys(changedFields).map((key)=> {
          let newObj = {}
          newObj[key] = changedFields[key].value
          Object.assign(this.bisHouse, newObj)
        })
      },
      handleSubmit() {
        this.$refs['baseForm'].form.validateFields((err, values) => {
          if (err) {
            this.$notification['error']({
              message: '参数未通过校验'
            })
          } else {
            Object.assign(this.bisHouse, values.baseForm)
            const bisHouseVo = {
              bisHouse: this.bisHouse,
              coverId: this.coverId,
              slideIds: this.slideList.map(item => item.uid)
            }
            console.log(this.slideIds)
            if(this.bisHouse.id) {
              // 编辑
              editHouse(bisHouseVo).then(res => {
                if(res.success) {
                  this.$router.push({path:'/house', replace: true})
                }
              })
            }else{
              // 添加
              addHouse(bisHouseVo).then(res => {
                if(res.success) {
                  this.$router.push({path:'/house'})
                }
              })
            }
          }
        })
      },
      watchCoverId(coverId) {
        this.coverId = coverId
      },
      removeSlide(slide) {
        this.slideList.findIndex(item => item.uid === slide.id)
        console.log('slide:', slide)
        this.slideList.splice(this.slideList.findIndex(item => item.uid === slide.uid), 1)
        console.log(this.slideList.length)
      },
      afterSlideUpload(info) {
        if (info.file.status === 'done') {
          const item = info.file.response.result
          const slide = {uid:item.id, name:item.originalFileName, status:'done', url:window._CONFIG['domianURL']+'/'+item.relativePath, thumbUrl: window._CONFIG['domianURL']+'/'+item.relativePath}
          this.slideList.push(slide)
        }
      }
    },
    computed: {
      getTitle() {
        return { value: this.bisHouse.title }
      },
      getRegion() {
        return { value: this.bisHouse.region }
      },
      getStructure() {
        return { value: this.bisHouse.structure }
      },
      getSellType() {
        return { value: this.bisHouse.sellType }
      },
      getAddress() {
        return { value: this.bisHouse.address }
      },
      getMoney() {
        return { value: this.bisHouse.money }
      },
      getUnit() {
        return { value: this.bisHouse.unit }
      },
      houseContent() {
        return this.bisHouse.content
      }
    }
  }
</script>

<style scoped>
  .r-layout-slide {
    background: none;
  }
</style>